#include <windows.h>
#include <stdio.h>
#include <wingdi.h>
#include <time.h>

void Screenshoot()
{
	BITMAPINFO bmi;
	BITMAPFILEHEADER bfh;

	int nWidth;
	int nHeight;

	HWND hWnd;
	HDC hdc ;
	HDC memDC;
	HBITMAP hbm ;
	HBITMAP hbmOld;
	BYTE *pbBits;

	HANDLE hfile;
	DWORD dwWritten;

	nWidth = GetSystemMetrics(SM_CXSCREEN);
	nHeight = GetSystemMetrics(SM_CYSCREEN);

	hWnd = GetDesktopWindow();
	hdc = GetDC(hWnd);
	memDC = CreateCompatibleDC(hdc);
	hbm = CreateCompatibleBitmap(hdc, nWidth, nHeight);
	hbmOld = (HBITMAP)SelectObject(memDC, hbm);

	BitBlt(memDC, 0, 0, nWidth, nHeight, hdc, 0, 0, SRCCOPY);

	ZeroMemory(&bmi, sizeof(bmi));

	bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	bmi.bmiHeader.biWidth = nWidth;
	bmi.bmiHeader.biHeight = nHeight;
	bmi.bmiHeader.biBitCount = 24;
	bmi.bmiHeader.biPlanes = 1;
	bmi.bmiHeader.biCompression = BI_RGB;
	bmi.bmiHeader.biSizeImage = 32 * nWidth * nHeight / 8;

	pbBits = (byte *) malloc(bmi.bmiHeader.biSizeImage); ;

	GetDIBits( memDC,
	hbm,
	0,
	bmi.bmiHeader.biHeight,
	pbBits,
	&bmi,
	DIB_RGB_COLORS );

	bfh.bfType = ('M' << 8) + 'B';
	bfh.bfSize = sizeof(BITMAPFILEHEADER) +
	bmi.bmiHeader.biSizeImage +
	sizeof(BITMAPINFOHEADER);
	bfh.bfReserved1 = 0;
	bfh.bfReserved2 = 0;
	bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);


    CreateDirectory("Screenshots", NULL);
    time_t tiempo = time(0);
    struct tm *tlocal = localtime(&tiempo);
    char output[128];
    strftime(output,128,"Screenshots\\%d-%m-%y %H_%M_%S.bmp",tlocal);

	hfile = CreateFile( (output),
	GENERIC_WRITE,
	0,
	0,
	OPEN_ALWAYS,
	0,
	0 );

	WriteFile(hfile,&bfh, sizeof(bfh), &dwWritten, NULL);
	WriteFile(hfile,&bmi.bmiHeader, sizeof(BITMAPINFOHEADER), &dwWritten, NULL);
	WriteFile(hfile,pbBits, bmi.bmiHeader.biSizeImage, &dwWritten, NULL);

	CloseHandle(hfile);

	SelectObject(memDC, hbmOld);
	DeleteDC(memDC);
	ReleaseDC(hWnd,hdc);
	DeleteObject(hbm);

	free(pbBits);
}
